package com.yanqu.road.entity.activity.xiuxian.data;

import com.yanqu.road.entity.activity.xiuxian.sort.CrossXiuXianRankSort;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;

public class CrossXiuXianRankListModel {

    private Comparator<CrossXiuXianRank> rankSort = new CrossXiuXianRankSort();

    private LinkedList<CrossXiuXianRank> rankList = new LinkedList<>();

    public void rankChange(CrossXiuXianRank rank) {
        synchronized (this) {
            boolean change = false;
            boolean find = false;
            for (CrossXiuXianRank tmpRank : rankList) {
                // 找到了
                if (Objects.equals(tmpRank.getId(), rank.getId())) {
                    tmpRank.setValue(rank.getValue());
                    tmpRank.setParam(rank.getParam());
                    tmpRank.setTime(rank.getTime());
                    change = true;
                    find = true;
                    break;
                }
            }
            if (!find) {
                rankList.add(rank);
                change = true;
            }
            if (change) {
                rankSort();
            }
        }
    }

    public LinkedList<CrossXiuXianRank> getRankList() {
        return new LinkedList<>(rankList);
    }

    public void setRankList(LinkedList<CrossXiuXianRank> rankList) {
        synchronized (this) {
            this.rankList = rankList;
            rankSort();
        }
    }

    public int getMyRank(String id) {
        int rank = -1;
        int index = 0;
        synchronized (this) {
            for(CrossXiuXianRank userRank : rankList){
                if(userRank.getId().equals(id)){
                    rank = index + 1;
                    break;
                }
                index++;
            }
        }
        return rank;
    }

    /**
     * 排序，记得加锁
     */
    private void rankSort() {
        rankList.sort(rankSort);
    }

}
